import UploadImage from '@/components/Upload';
import { addDoctorAPI, delDoctorAPI, delIdsAPI, loadData, modifyDoctorAPI } from '@/services/users';
import { dalImg } from '@/utils/tools';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  PageContainer,
  ProForm,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
//@ts-ignore
import { FormattedMessage } from '@umijs/max';
import { Button, Popconfirm, Space, message } from 'antd';
import { useEffect, useRef, useState } from 'react';

function Users() {
  // 编辑器内容
  //展示上传图片地址
  const [imageUrl, setImageUrl] = useState<string>();
  //模态框状态
  const [isShow, setIsShow] = useState(false);
  //操作表单
  const [myForm] = ProForm.useForm();
  const [selRowKeys, SetSelRowKeys] = useState([]);

  const [editID, setEditID] = useState('');
  const actionRef = useRef<any>();

  //模态框关闭后需要清除的数据
  useEffect(() => {
    if (!isShow) {
      setEditID('');
      setImageUrl('');
    }
  }, [isShow]);
  return (
    <PageContainer>
      <ProTable
        //定义actionRef可以用来改变数据后刷新表单
        actionRef={actionRef}
        //key值
        rowKey="id"
        rowSelection={{
          selectedRowKeys: selRowKeys,
          onChange(selectedRowKeys: any) {
            // console.log(selectedRowKeys);  选中的key值
            //
            SetSelRowKeys(selectedRowKeys);
            // console.log(selectedRowKeys, selectedRows, info);
          },
        }}
        //边框
        bordered
        //请求表格数据
        request={loadData}
        //右上角新增按钮
        toolBarRender={() => {
          const tools = [
            <Button
              onClick={() => {
                setIsShow(true);
              }}
              size="small"
              type="primary"
              key={crypto.randomUUID()}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
            </Button>,
          ];
          if (selRowKeys.length > 0)
            tools.push(
              <Popconfirm
                title="批量删除"
                description="确认删除选中的?"
                onConfirm={() => {
                  delIdsAPI(selRowKeys)
                    .then((res) => {
                      console.log(res);
                      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
                      res.success ? message.success('批量删除成功') : null;
                      actionRef.current?.reload(); // 重新加载数据
                      SetSelRowKeys([]);
                    })
                    .catch(() => {
                      message.error('删除失败');
                    });
                }}
                onCancel={() => {
                  message.error('删除取消');
                  SetSelRowKeys([]);
                }}
                okText="确定"
                cancelText="取消"
              >
                <Button type="primary" danger icon={<DeleteOutlined />} key={123}>
                  批量删除
                </Button>
              </Popconfirm>,
            );
          return tools;
        }}
        //每一列表示的数据
        columns={[
          {
            title: '序号',
            width: '60px',
            align: 'center',
            //search表示是否可搜索
            search: false,
            //return返回值作为数据填充当前列，参数一、参数二表示接口返回的数组中的每一项数据，参数三表示当前行表示的索引(从0开始)
            render(value, item, index) {
              return index + 1;
            },
          },
          {
            title: '头像',
            align: 'center',
            search: false,
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            render(value: any, item: any, index: any) {
              // console.log(value);
              return <img width="50px" src={dalImg(value.avatar)}></img>;
            },
          },
          {
            title: '用户名',
            align: 'center',
            dataIndex: 'userName',
          },
          {
            title: '昵称',
            align: 'center',
            dataIndex: 'nickName',
          },
          {
            title: '电话',
            align: 'center',
            dataIndex: 'mobile',
          },
          {
            title: '地址',
            //dataIndex表示当前列数据在数据项中对应的路径(属性名表示的属性值)
            render(v, c) {
              return c.address ? c.address : '未知';
            },
            align: 'center',
            ellipsis: true,
            search: false,
          },
          {
            title: '操作',
            align: 'center',
            search: false,
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            render(value: any, item: any, index: any) {
              return (
                <Space>
                  <Button
                    type="primary"
                    onClick={() => {
                      setIsShow(true);
                      myForm.setFieldsValue(item);
                      setEditID(item.id);
                      setImageUrl(dalImg(item.avatar));
                    }}
                    icon={<EditOutlined />}
                  ></Button>
                  <Popconfirm
                    title="删除"
                    description="是否确认删除？"
                    onConfirm={() => {
                      delDoctorAPI(value.id).then(() => {
                        actionRef.current.reload();
                      });
                    }}
                    okText="确认"
                    cancelText="取消"
                  >
                    <Button type="primary" danger icon={<DeleteOutlined />}></Button>
                  </Popconfirm>
                </Space>
              );
            },
          },
        ]}
      ></ProTable>
      {/* 模态框 */}
      <ModalForm
        form={myForm}
        width="650px"
        //modalProps值是一个对象，maskClosable表示点击遮罩层是否关闭模态框，destroyOnClose表示关闭模态框是否清空其中的数据
        modalProps={{ maskClosable: false, destroyOnClose: true }}
        //open控制模态框弹出
        open={isShow}
        //open 改变时触发
        onOpenChange={setIsShow}
        onFinish={async (v) => {
          // v 表示由表单中name属性值组成的对象
          // console.log(v);
          if (editID) {
            //修改
            await modifyDoctorAPI(editID, { ...v, avatar: imageUrl })
              .then(() => {
                actionRef.current.reload();
                message.success('ok');
                setIsShow(false);
              })
              .catch(() => message.error('已存在的用户名'));
          } else {
            //新增
            await addDoctorAPI({ ...v, avatar: imageUrl });
            actionRef.current.reload();
            message.success('ok');

            setIsShow(false);
          }
          //数据改变之后刷新
        }}
      >
        <ProForm.Group>
          <ProFormText
            width="md"
            name="userName"
            label="用户名"
            rules={[
              {
                required: true,
                message: '用户名不能为空',
              },
            ]}
            placeholder="请输入用户名"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText width="md" name="nickName" label="昵称" placeholder="请输入昵称" />
        </ProForm.Group>
        <ProForm.Item label="头像">
          {/* 图片上传 */}
          <UploadImage imageUrl={imageUrl} setImageUrl={setImageUrl} />
        </ProForm.Item>

        <ProForm.Group>
          <ProFormTextArea width="lg" name="address" label="地址" placeholder="请输地址" />
        </ProForm.Group>
      </ModalForm>
    </PageContainer>
  );
}

export default Users;
